package cc.ucanuup.config.security;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import cc.ucanuup.config.security.token.MyUsernamePasswordAuthenticationToken;
import cc.ucanuup.service.base.entity.UpUser;
import cc.ucanuup.service.base.inter.UpUserService;
import cc.ucanuup.service.base.inter.UserPowerService;

/**
 * 文件名： cc.ucanuup.config.security.CustomAuthenticationProvider.java
 * 作者：   WenBin
 * 日期：   2018年2月12日
 * 功能说明： 这里是用于自定义的用户登陆拦截
 *
 * =========================================================
 * 修改记录：
 * 修改作者    日期      修改内容
 *
 *
 * =========================================================
 *  Copyright (c) 2010-2011 .All rights reserved.
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

	private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private HttpSession session;

	@Autowired
	private UpUserService upUserService;
	@Autowired
	private UserPowerService userPowerService;

	/**
	 * Validate user info is correct form database
	 *
	 * @param authentication
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		try {
			String username = authentication.getName();
			String password = authentication.getCredentials().toString();
			List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			logger.info("校验用户信息"+username+"密码："+password);
			UpUser ss = upUserService.findSupplierByName(username);
			// 用户信息
			String spCode = null;
			String spId = null;
			boolean spLogin = false;
			String spName = null;
			String userId = null;
			String userName = null;
			String loginPage = MyLoginFilter.spCodeThread.get().getLoginType();
			// 检查用户名密码是否正确
			if (ss == null) {
				logger.error("{} login failed, username or password is wrong", username);
				throw new BadCredentialsException("账号不存在！");
			}/* else if (!ss.getEnabled()) {
				throw new AccountExpiredException("Account had expired");
			}*/else{
				String password2 = ss.getUserPassword();
				if(password!=null && password2.equals(password)){
					UpUser spMessage = upUserService.findSupplierByName(MyLoginFilter.spCodeThread.get().getSpcode());
					if(ss.getUserType().equals("1") && MyLoginFilter.spCodeThread.get()!= null && spMessage!=null && MyLoginFilter.spCodeThread.get().isFlag()){ // 获取指定供应商的权限
						spCode = spMessage.getUserAccount();
						spId = spMessage.getId();
						spLogin = true;
						spName = spMessage.getSupplierShortName();
						userId = ss.getId();
						userName = ss.getSupplierShortName();
						Set<String> permission = userPowerService.getPermissionsByUserAccount(spMessage);
						for (String str : permission) {
							GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(str);
							grantedAuthorities.add(grantedAuthority);
						}
					}else{ // 获取自身的权限
						spCode = ss.getUserAccount();
						spId = ss.getId();
						spLogin = false;
						spName = ss.getSupplierShortName();
						userId = ss.getId();
						userName = ss.getSupplierShortName();
						Set<String> permission = userPowerService.getPermissionsByUserAccount(ss);
						for (String str : permission) {
							GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(str);
							grantedAuthorities.add(grantedAuthority);
						}
					}
				}else{
					throw new BadCredentialsException("密码不正确！");
				}
			}
			// 用户信息有效时将其放入 session 中
			MyUsernamePasswordAuthenticationToken auth = new  MyUsernamePasswordAuthenticationToken(username, password, grantedAuthorities);
			auth.setSpCode(spCode);
			auth.setSpId(spId);
			auth.setSpLogin(spLogin);
			auth.setSpName(spName);
			auth.setUserId(userId);
			auth.setUserName(userName);
			auth.setLoginPage(loginPage);
			//Authentication auth = new UsernamePasswordAuthenticationToken(username, password, grantedAuthorities);
			return auth;
		} catch (Exception e) {
			throw new BadCredentialsException("登陆信息异常！");
		}
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

}